package com.bff.gaia.client.cli;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class NettyClients {
	public void connect(int port,String host,String[] strings,FileUploadFile f) throws Exception
	{
		String filePath="";
		for(int i=0; i<strings.length; i++)
		{
			if(strings[i].contains(".") || strings[i].contains("\\"))
			{
				filePath+=strings[i];
				System.out.println("文件的绝对路径为："+strings[i]);
				System.out.println("文件的args参数为："+f.getInput());
				break;
			}
		}
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class)
				.option(ChannelOption.TCP_NODELAY, true)
				.handler(new ChannelInitializer<Channel>() {

					@Override
					protected void initChannel(Channel ch) throws Exception {
						ch.pipeline().addLast(new ObjectEncoder());
						ch.pipeline()
							.addLast(
								new ObjectDecoder(
									ClassResolvers
										.weakCachingConcurrentResolver(null)));
						ch.pipeline()
							.addLast(
								new ClientHandler(strings,f));
					}
				});
			ChannelFuture ff = b.connect(host, port).sync();
			ff.channel().closeFuture().sync();
			System.out.println("FileUploadClient connect()结束");
		} finally {
			group.shutdownGracefully();
		}
	}


}